package qdu.edu.com.fushanf4.service.count;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * 计数，累加
 */
public class TextIntWritableCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
    private final IntWritable valueOut = new IntWritable();

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        int sum = 0;

        for (IntWritable value : values) {
            sum += value.get();
        }

        valueOut.set(sum);
        context.write(key, valueOut);
    }

    /**
     * 多个Driver类使用了该Reducer类，产生了内容耦合，此处用来消除内容耦合
     * @param job Job
     */
    public static void setReduceOfAll(Job job) {
        job.setReducerClass(TextIntWritableCountReducer.class);

        // 本地处理
        job.setCombinerClass(TextIntWritableCountReducer.class);

        // 设置输入
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
    }
}
